<template>
  <div class="ed-box table-box card">
    <div class="so-head">
      <span class="fsize16">{{ isEdit ? "编辑原料" : "新增原料" }}</span>
      <div>
        <el-button @click="router.go(-1)">取消</el-button>
        <el-button v-if="isEdit" @click="onSubmit" type="primary">保存</el-button>
        <el-button v-else @click="onSubmit" type="primary">新增保存</el-button>
      </div>
    </div>

    <el-form :model="waresForm" label-width="100px" :rules="couponRules" ref="ruleFormRef">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="基本资料" name="first">
          <div class="flx-default">
            <div class="width400">
              <!-- <el-form-item label="销售方式" prop="saleType">
                <el-radio-group v-model="waresForm.saleType">
                  <el-radio-button :label="1">普通</el-radio-button>
                  <el-radio-button :label="2">称重销售</el-radio-button>
                  <el-radio-button :label="3">按数量销售</el-radio-button>
                </el-radio-group>
              </el-form-item> -->
              <el-form-item label="原料条码" :prop="`products[${0}].barcode`" :rules="couponRules.barcode">
                <el-input class="w100" v-model="waresForm.products[0].barcode" placeholder="请填写" />
              </el-form-item>
              <el-form-item label="原料名称" prop="name">
                <el-input class="w100" v-model="waresForm.name" placeholder="请填写" />
              </el-form-item>
              <el-form-item label="规格型号" :prop="`products[${0}].spesDesc`" :rules="couponRules.spesDesc">
                <el-input class="w100" v-model="waresForm.products[0].spesDesc" placeholder="请填写" />
              </el-form-item>
              <el-form-item label="采购价" prop="purPrice">
                <el-input-number class="w100" v-model="waresForm.products[0].purPrice" :controls="false" />
              </el-form-item>
            </div>
            <div class="width400">
              <!-- <el-form-item label="原料PLU" prop="plu" v-if="waresForm.saleType !== 1">
                <el-input-number class="w100" v-model="waresForm.plu" placeholder="1-6位数字" :controls="false" />
              </el-form-item> -->
              <!-- <el-form-item v-else><div style="color: #ffffff">占位符</div></el-form-item> -->
              <el-form-item label="原料类别" prop="goodsCategoryId">
                <div class="flx-default w100">
                  <el-tree-select
                    class="w100"
                    node-key="value"
                    v-model="waresForm.goodsCategoryId"
                    :data="waresCategory"
                    :render-after-expand="false"
                    check-strictly
                  />
                  <el-button type="primary" @click="openWaresCategoryDialog('新增', { isShow: true })">新增</el-button>
                </div>
              </el-form-item>
              <el-form-item label="货号" prop="articleNo">
                <el-input class="w100" v-model="waresForm.articleNo" placeholder="请填写" />
              </el-form-item>
              <el-form-item label="单位" :prop="`products[${0}].unitName`" :rules="couponRules.unitName">
                <el-input class="w100" v-model="waresForm.products[0].unitName" placeholder="请填写" />
              </el-form-item>

              <el-form-item label="供应商" prop="supplierId">
                <el-select class="w100" v-model="waresForm.supplierId">
                  <el-option v-for="audience in supplierList" :key="audience.id" :label="audience.name" :value="audience.id" />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div>
            <!-- <el-text class="ml30" type="primary">价格信息(*必填信息)</el-text> -->
            <el-text class="ml30" type="primary">包装规格</el-text>
            <el-divider border-style="dashed" />
          </div>
          <div class="width800">
            <el-form-item label="" label-width="0">
              <el-table :data="tbData" border>
                <el-table-column prop="barcode" label="条形码" align="center">
                  <template #default="scope">
                    <el-form-item :prop="`products[${scope.$index + 1}].barcode`" :rules="couponRules.barcode">
                      <el-input v-model="scope.row.barcode" placeholder="条形码" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="spesDesc" label="规格名称" align="center">
                  <template #default="scope">
                    <el-form-item :prop="`products[${scope.$index + 1}].spesDesc`" :rules="couponRules.spesDesc">
                      <el-input v-model="scope.row.spesDesc" placeholder="规格名称" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="unitName" label="规格单位" align="center">
                  <template #default="scope">
                    <el-form-item :prop="`products[${scope.$index + 1}].unitName`" :rules="couponRules.unitName">
                      <el-input v-model="scope.row.unitName" placeholder="规格单位" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="convert" label="转换系数" align="center">
                  <template #default="scope">
                    <el-input-number :controls="false" :min="0" v-model="scope.row.convert" placeholder="转换系数" />
                  </template>
                </el-table-column>
                <el-table-column prop="purPrice" label="采购价" align="center">
                  <template #default="scope">
                    <el-input-number class="w100" :controls="false" v-model="scope.row.purPrice" />
                  </template>
                </el-table-column>
                <el-table-column prop="operate" label="操作" align="center">
                  <template #default="scope">
                    <!-- <el-text v-if="scope.$index === 0" type="primary">默认</el-text> -->
                    <el-button type="danger" size="small" @click="delSpecRow(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-button class="mt10" type="primary" v-if="waresForm.saleType === 1" @click="addSpec">添加规格</el-button>
            <!-- <div class="width400">
              <el-form-item label="配送价" prop="rmoPrice">
                <el-input-number class="w100" v-model="waresForm.products[0].rmoPrice" :controls="false" />
              </el-form-item>
              <el-form-item label="电商价" prop="mallPrice">
                <el-input-number class="w100" v-model="waresForm.products[0].mallPrice" :controls="false" />
              </el-form-item>
              <el-form-item label="会员积分" prop="pointValue">
                <el-input type="number" :min="0" v-model.number="waresForm.pointValue">
                  <template #append>
                    <el-select v-model="waresForm.pointType" style="width: 150px">
                      <el-option label="分(固定积分)" :value="1" />
                      <el-option label="%(销售额百分比)" :value="2" />
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
            </div> -->
          </div>
          <div>
            <!-- <el-text class="ml30" type="primary">其他信息(选填项)</el-text> -->
            <!-- <el-divider border-style="dashed" /> -->
          </div>
          <div class="flx-default">
            <div class="width400">
              <!-- <el-form-item label="供应商" prop="supplierId">
                <el-select class="w100" v-model="waresForm.supplierId">
                  <el-option v-for="audience in supplierList" :key="audience.id" :label="audience.name" :value="audience.id" />
                </el-select>
              </el-form-item> -->
              <!-- <el-form-item label="组织机构" prop="organizationId">
                <el-select v-model="waresForm.organizationId" placeholder="请选择" class="w100">
                  <el-option v-for="category in organization" :key="category.name" :label="category.name" :value="category.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="原料品牌" prop="brandId">
                <div class="flx-default w100">
                  <el-select class="w100" v-model="waresForm.brandId">
                    <el-option v-for="brand in brands" :key="brand.id" :label="brand.name" :value="brand.id" />
                  </el-select>
                  <el-button type="primary" @click="openWaresBrandDialog('新增', { isShow: true })">新增</el-button>
                </div>
              </el-form-item>
              <el-form-item label="经营方式" prop="operationMode">
                <el-select class="w100" v-model="waresForm.operationMode">
                  <el-option label="购销" :value="1" />
                  <el-option label="代销" :value="2" />
                </el-select>
              </el-form-item> -->
            </div>
            <!-- <div class="width400">
              <el-form-item label="数字助记码" prop="helpCode">
                <el-input class="w100" v-model="waresForm.helpCode" placeholder="请填写" />
              </el-form-item>
              <el-form-item label="拼音助记码" prop="pinYin">
                <el-input class="w100" v-model="waresForm.pinYin" placeholder="请填写" />
              </el-form-item>
              <el-form-item label="有效期" prop="effectiveDays">
                <el-input
                  class="w100"
                  v-model="waresForm.effectiveDays"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  placeholder="请输入"
                >
                  <template #append>
                    <div>天</div>
                  </template>
                </el-input>
              </el-form-item>
            </div> -->
          </div>
        </el-tab-pane>
        <!-- <el-tab-pane label="辅助信息" name="second">
          <div class="width400">
            <el-form-item label="一级会员价" prop="vip1Price">
              <el-input-number class="width300" v-model="waresForm.products[0].vip1Price" :controls="false" />
            </el-form-item>
            <el-form-item label="二级会员价" prop="vip2Price">
              <el-input-number class="w100" v-model="waresForm.products[0].vip2Price" :controls="false" />
            </el-form-item>
            <el-form-item label="三级会员价" prop="vip3Price">
              <el-input-number class="w100" v-model="waresForm.products[0].vip3Price" :controls="false" />
            </el-form-item>
            <el-form-item label="产地" prop="producer">
              <el-input v-model="waresForm.producer" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="参与折扣" prop="isDiscount">
              <el-radio-group v-model="waresForm.isDiscount">
                <el-radio-button :label="true">参与</el-radio-button>
                <el-radio-button :label="false">不参与</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="管理库存" prop="isStock">
              <el-radio-group v-model="waresForm.isStock">
                <el-radio-button :label="true">是</el-radio-button>
                <el-radio-button :label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="时价原料" prop="isRulingPrice">
              <el-radio-group v-model="waresForm.isRulingPrice">
                <el-radio-button :label="true">否</el-radio-button>
                <el-radio-button :label="false">是</el-radio-button>
              </el-radio-group>
              <el-text class="ml10" type="info">说明：在收银机销售时候可以进行实时变价</el-text>
            </el-form-item>
            <el-form-item label="是否积分" prop="isIntegral">
              <el-radio-group v-model="waresForm.isIntegral">
                <el-radio-button :label="false">否</el-radio-button>
                <el-radio-button :label="true">是</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="导购提成" prop="commissionType">
              <el-radio-group v-model="waresForm.commissionType">
                <el-radio-button :label="1">不提成</el-radio-button>
                <el-radio-button :label="2">按比率</el-radio-button>
                <el-radio-button :label="3">按金额</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="" prop="commissionValue" v-if="waresForm.commissionType !== 1">
              <el-input
                class="width320"
                v-model="waresForm.commissionValue"
                oninput="value=value.replace(/[^0-9.]/g,'')"
                placeholder="请输入"
              >
                <template #append>
                  <div v-if="waresForm.commissionType === 2">%</div>
                  <div v-if="waresForm.commissionType === 3">￥</div>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="备注信息" prop="remark">
              <el-input
                class="width400"
                v-model="waresForm.remark"
                :autosize="{ minRows: 4, maxRows: 10 }"
                type="textarea"
                placeholder="请输入内容..."
              />
            </el-form-item>
          </div>
        </el-tab-pane>-->
        <!-- <el-tab-pane label="原料详情" name="third">
          <el-form-item label="" label-width="0" prop="intro">
            <WangEditor v-model:value="waresForm.intro" height="400px" />
          </el-form-item>
        </el-tab-pane> -->
        <!-- <el-tab-pane label="展示图片" name="fourth">
          <el-form-item label="原料封面" prop="image">
            <UploadImg v-model:image-url="waresForm.image" :file-size="3">
              <template #empty>
                <el-icon><Picture /></el-icon>
                <span>请上传封面图</span>
              </template>
              <template #tip> 图片大小不能超过 3M </template>
            </UploadImg>
          </el-form-item>
          <el-form-item label="原料图集" prop="images">
            <UploadImgs v-model:file-list="waresForm.images">
              <template #empty>
                <el-icon><Picture /></el-icon>
                <span>请上传照片</span>
              </template>
              <template #tip> 照片大小不能超过 5M </template>
            </UploadImgs>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="包装规格" name="fifth"> </el-tab-pane> -->
      </el-tabs>
    </el-form>
    <WaresCategoryDialog ref="waresCategoryDialogRef" />
    <WaresBrandDialog ref="waresBrandDialogRef" />
  </div>
</template>
<script setup lang="ts" name="waresEdit">
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { editWares, createWares, getEditWares } from "@/api/modules/inventory";
import type { FormInstance } from "element-plus";
import { transformCategories } from "@/utils";
import { getOrganizationList } from "@/api/modules/operation";
import UploadImg from "@/components/Upload/Img.vue";
import UploadImgs from "@/components/Upload/Imgs.vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { getWaresBrandList, getWaresCategoryList, getSupplierList, createWaresCategory } from "@/api/modules/inventory";
import WaresCategoryDialog from "@/views/inventory/components/WaresCategoryDialog.vue";
import { Inventory } from "@/api/interface";
import WaresBrandDialog from "@/views/inventory/components/WaresBrandDialog.vue";

const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const isEdit = ref(false);
const activeName = ref("first");
const waresForm = reactive({
  id: 0,
  saleType: 1,
  bn: "",
  name: "",
  image: "",
  images: [],
  pinYin: "",
  helpCode: "",
  goodsCategoryId: 1,
  brandId: 1,
  articleNo: "",
  plu: "",
  commissionValue: 0,
  organizationId: 0,
  intro: "",
  effectiveDays: "",
  isStock: true,
  operationMode: 1,
  supplierId: 1,
  producer: "",
  isDiscount: true,
  isRulingPrice: true,
  isIntegral: false,
  commissionType: 1,
  pointValue: 0,
  pointType: 1,
  remark: "",
  products: [
    {
      barcode: "",
      spesDesc: "",
      unitName: "",
      mallPrice: 0,
      convert: 1,
      posPrice: 0,
      purPrice: 0,
      rmoPrice: 0,
      vipPrice: 0,
      vip1Price: 0,
      vip2Price: 0,
      vip3Price: 0,
      onLine: true
    }
  ]
});
const couponRules = ref({
  name: [{ required: true, message: "请填写原料名称" }],
  barcode: [{ required: true, message: "请填写原料条码" }],
  unitName: [{ required: true, message: "请填写规格单位" }],
  spesDesc: [{ required: true, message: "请填写规格名称" }]
  // price: [
  //   { required: true, message: "请填写价格" },
  //   { pattern: /(^[1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/, message: "价格大于0且只能有两位小数点" }
  // ]
});

const addSpec = () => {
  waresForm.products.push({
    barcode: "",
    spesDesc: "",
    unitName: "",
    convert: 1,
    posPrice: 0,
    purPrice: 0,
    rmoPrice: 0,
    vip1Price: 0,
    vip2Price: 0,
    vip3Price: 0,
    onLine: true
  });
};

const delSpecRow = (index: number) => {
  waresForm.products.splice(index, 1);
};

const waresCategoryDialogRef = ref<InstanceType<typeof WaresCategoryDialog> | null>(null);
const openWaresCategoryDialog = (title: string, row: Partial<Inventory.ResWaresCategoryList> = {}) => {
  const params = {
    title,
    row: { ...row },
    isView: false,
    api: createWaresCategory,
    categories: waresCategory.value,
    getTableList: getWCategoryList
  };
  waresCategoryDialogRef.value?.acceptParams(params);
};
const getWCategoryList = async () => {
  const { data } = await getWaresCategoryList();
  waresCategory.value = transformCategories(data, "name", "id", true);
};

const waresBrandDialogRef = ref<InstanceType<typeof WaresBrandDialog> | null>(null);
// const openWaresBrandDialog = (title: string, row: Partial<Inventory.ResWaresBrandList> = {}) => {
//   const params = {
//     title,
//     row: { ...row },
//     isView: false,
//     api: createWaresBrand,
//     getTableList: getWBrandLs
//   };
//   waresBrandDialogRef.value?.acceptParams(params);
// };

// const getWBrandLs = async () => {
//   const { data } = await getWaresBrandList({ pageNum: 1, pageSize: 9999 });
//   brands.value = data.list;
// };

const onSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (isEdit.value) {
        await editWares(waresForm).then(() => {
          router.push({
            path: "/inventory/waresList",
            query: {
              upList: true
            }
          });
        });
      } else {
        await createWares(waresForm).then(() => {
          router.push({
            path: "/inventory/waresList",
            query: {
              upList: true
            }
          });
        });
      }
    } catch (error) {
      console.log(error);
    }
  });
};
const brands = ref([]);
const waresCategory = ref([]);
const supplierList = ref([]);
const organization = ref<any>([]);

const tbData = computed(() => {
  return waresForm.products.filter((im, ix) => ix !== 0);
});

onMounted(async () => {
  try {
    const [brand, category, supplier, orz] = await Promise.all([
      getWaresBrandList({ pageNum: 1, pageSize: 9999 }),
      getWaresCategoryList(),
      getSupplierList({ pageNum: 1, pageSize: 9999, supplierCode: 0 }),
      getOrganizationList()
    ]);
    brands.value = brand.data.list;
    supplierList.value = supplier.data.list;
    organization.value = orz.data.list;
    waresCategory.value = transformCategories(category.data, "name", "id", true);
    if (route.query.id) {
      isEdit.value = true;
      getEditWares({ id: route.query.id }).then(res => {
        Object.keys(waresForm).forEach(key => {
          if (res.data.hasOwnProperty(key)) {
            waresForm[key] = res.data[key];
          }
        });
      });
    } else {
      waresForm.brandId = brand.data.list.length > 0 ? brand.data.list[0].id : "";
      waresForm.goodsCategoryId = waresCategory.value[0].value;
      waresForm.supplierId = supplier.data.list.length > 0 ? supplier.data.list[0].id : "";
      waresForm.organizationId = orz.data.list.length > 0 ? orz.data.list[0].id : "";
    }
  } catch (error) {
    // 错误处理逻辑
    console.error("An error occurred:", error);
  }
});
</script>
<style lang="scss" scoped>
.ed-box {
  position: relative;
  .so-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 10px;
    border-bottom: 2px #e4e7ed solid;
  }
  .fod-btn-box {
    position: fixed;
    bottom: 52px;
    left: 50%;
    display: flex;
    justify-content: center;
    background-color: #ffffff;
    transform: translateX(-50%);
  }
}
</style>
